﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "src/publics.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMainWindow::centralWidget()->setMouseTracking(true);
    this->setWindowTitle(u8"XY散点图");
    clipboard = QApplication::clipboard(); //复制到剪贴板，可以粘贴到excel
    plot = new MultPlot;
    m_group = new QButtonGroup;
    m_group_heng = new QActionGroup(this);
    m_group_ver = new QActionGroup(this);
    m_group_heng->addAction(ui->actionX);
    m_group_heng->addAction(ui->actionY);
    m_group_heng->addAction(ui->actionZ);

    m_group_ver->addAction(ui->actionX_2);
    m_group_ver->addAction(ui->actionY_2);
    m_group_ver->addAction(ui->actionZ_2);


    m_group_heng->setExclusive(true);
    m_group_ver->setExclusive(true);

    ui->actionX->setChecked(true);  //设置一个默认选中的
    ui->actionY_2->setChecked(true);  //设置一个默认选中的

    connect(m_group, QOverload<int>::of(&QButtonGroup::buttonClicked),
          [=](int id){
        // qDebug()<<id;
        if(curIsPos)
            ReflushChart();
    });
    initUIs();
    plot->SetStyle(S_NONE);
}


void MainWindow::initUIs()
{
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    table_widget_menu = new QMenu(ui->tableWidget);
    QAction *action = new QAction(u8"插入", this);
    connect(action, SIGNAL(triggered()), this, SLOT(slotActionInsert()));
    table_widget_menu->addAction(action);
    action = new QAction(u8"删除行", this);
    connect(action, SIGNAL(triggered()), this, SLOT(slotActionRemove()));
    table_widget_menu->addAction(action);
    action = new QAction(u8"删除", this);
    connect(action, SIGNAL(triggered()), this, SLOT(slotActionRemoveAItem()));
    table_widget_menu->addAction(action);
    action = new QAction(u8"清空列", this);
    connect(action, SIGNAL(triggered()), this, SLOT(slotActionCleanCol()));
    table_widget_menu->addAction(action);

    ui->chartLayout->addWidget(plot);
    ui->chartLayout->setStretch(0,0);
    ui->chartLayout->setStretch(1,1);
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //ui->tableWidget->setCurrentItem(0,0);
    ui->tableWidget->setCurrentCell(0,0);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);



}

// 显示XYZ
void MainWindow::getXYZ()
{
    plot->getBody()->legend->setVisible(true);
    plot->title->setText("X-Y");
    auto Serial_name = (m_group_heng->checkedAction()->text() +
                        m_group_ver->checkedAction()->text()).toStdString();
    Serial_name += "u8系列1";
    plot->setTitles(Serial_name,"");
    for(int col = 0;col < 3;col ++){
        int rows = ui->tableWidget->rowCount();
        QVector<double > vect;
        vect.clear();
        bool trans;
        for(int cc = 0;cc < rows;cc++){
            if(nullptr == ui->tableWidget->item(cc,col)
                    || ui->tableWidget->item(cc,col)->text().isEmpty()){
                continue;
            }else{
                QString text = ui->tableWidget->item(cc,col)->text();
                double value = text.toDouble(&trans);
                if(!trans) {
                    continue;
                }
                else  vect.push_back(value);
            }
        }
        plot->curData[col].swap(vect);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

//
void MainWindow::Copy2Clip()
{
    QList<QTableWidgetItem*> tableWidgetItem = ui->tableWidget->selectedItems();
      if(tableWidgetItem.count()==0) //如果没有选择，返回
         return;

    //选择范围
    int topRow ,buttomRow, leftColumn, rightColumn;
    QList<QTableWidgetSelectionRange> tableSelectRange= ui->tableWidget->selectedRanges();
    for(int i=0;i<tableSelectRange.count();i++)
    {
        topRow= tableSelectRange.at(i).topRow();
        buttomRow=tableSelectRange.at(i).bottomRow();
        leftColumn=tableSelectRange.at(i).leftColumn();
        rightColumn=tableSelectRange.at(i).rightColumn();
    }

    //复制到cliptext
    QString clipText;
    for (int i=topRow;i<=buttomRow;i++) {
        for (int j=leftColumn;j<=rightColumn;j++) {
            QString text;
            if( ui->tableWidget->item(i,j)!=nullptr )//这个很重要
                text = ui->tableWidget->item(i,j)->text();
            clipText.append(text);
            clipText.append("\t");
        }
        clipText.chop(1);//删除末尾一个字符
        clipText.append("\n");
    }
    clipboard->setText(clipText );
}

void MainWindow::Clip2Table(QString str)
{
    int ColCntq = ui->tableWidget->rowCount();
    QList<QString> RowStr = str.split("\n");
    if(ColCntq < RowStr.size()){
        int needInsert=0;
        for(auto p:RowStr){
            if(!p.isEmpty()){
                needInsert++;
            }
        }
        if(2<(needInsert-ColCntq)){
            ui->tableWidget->setRowCount(needInsert-ColCntq);
        }
    }

    QList<QTableWidgetSelectionRange> sRangeList = ui->tableWidget->selectedRanges();
       for(const auto &p : qAsConst(sRangeList)) {
           int ColCnt = ui->tableWidget->columnCount();
           QList<QString> RowStr = str.split("\n");
           int x = p.topRow();
           for(const auto &Row : qAsConst(RowStr)) {
               if(!Row.isEmpty()) {
                   QString sep;
                   if(Row.contains('\t')){
                       sep = '\t';
                   }else{
                       sep = ',';
                   }
                   QList<QString> ColStr = Row.split(sep);
                   int y = p.leftColumn();
                   for(const auto &Col : qAsConst(ColStr)) {
                       QTableWidgetItem* item = ui->tableWidget->item(x, y);
                       if(item == nullptr)
                           ui->tableWidget->setItem(x, y, new QTableWidgetItem(Col));
                       else
                           ui->tableWidget->item(x, y)->setText(Col);
                       if(y + 1 == ColCnt)
                           break;
                       ++y;
                   }
                   ++x;
               }
           }
       }
}

// 重新刷新曲线
void MainWindow::ReflushChart()
{
    clearCharts();
    getXYZ();
    bool ret;
    int x_Select_index = m_group_heng->checkedAction()->toolTip().toUInt(&ret);
    int y_Select_index = m_group_ver->checkedAction()->toolTip().toUInt(&ret);
    plot->creatChart(x_Select_index,y_Select_index,
                     m_group_heng->checkedAction()->text().toStdString(),
                     m_group_ver->checkedAction()->text().toStdString());
}

void MainWindow::keyPressEvent(QKeyEvent *e)
{
    if (e->modifiers() == (Qt::ControlModifier) )
    {
        if(e->key() == Qt::Key_C){
            Copy2Clip();
        }else if (e->key() == Qt::Key_V) {
            QString str = clipboard->text();
            Clip2Table(str);
        }else{}
    }
}


void MainWindow::slotActionInsert()
{
    int curRow = ui->tableWidget->currentRow();
    ui->tableWidget->insertRow(curRow);
}

void MainWindow::slotActionRemove()
{
    int curRow = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(curRow);
}

void MainWindow::slotActionRemoveAItem()
{
    int curRow = ui->tableWidget->currentRow();
    int curCol = ui->tableWidget->currentColumn();
    ui->tableWidget->removeCellWidget(curRow,curCol);
}

// 清空表的数据
void MainWindow::slotActionCleanCol()
{
    int curCol = ui->tableWidget->currentColumn();
    int ColCntq = ui->tableWidget->rowCount();
    for(int i = 0; i < ColCntq;i++){
        QTableWidgetItem* item = new QTableWidgetItem;
        ui->tableWidget->setItem(i,curCol,item);
    }
}


// 右键按钮
void MainWindow::on_tableWidget_customContextMenuRequested(const QPoint &pos)
{
    table_widget_menu->exec(QCursor::pos());
}

void MainWindow::on_actionReflush_triggered()
{
    ReflushChart();
}

void MainWindow::on_pb_set_clicked()
{
    bool transe;
    double step;
    if(!ui->le_xtick->text().isEmpty()){
        step = ui->le_xtick->text().toDouble(&transe);
        plot->xAxis->setTickStep(step);
        plot->xAxis->setTickCount(5);
        plot->xAxis->setTickStepStrategy(QCPAxisTicker::tssMeetTickCount);
    }

    if(!ui->le_ytick->text().isEmpty()){
        step = ui->le_ytick->text().toDouble(&transe);
        plot->yAxis->setTickStep(step);
        plot->yAxis->setTickCount(5);
        plot->yAxis->setTickStepStrategy(QCPAxisTicker::tssMeetTickCount);
    }

    plot->getBody()->replot();
}

void MainWindow::on_pb_autoTick_clicked()
{
   plot->getBody()->replot();
}

void MainWindow::on_actionReflush_2_triggered()
{
    plot->getBody()->graph(0)->rescaleAxes(true);
    plot->getBody()->replot();
}

void MainWindow::on_actionClean_triggered()
{
    ui->tableWidget->clear();
    ui->tableWidget->setCurrentCell(0,0);
}

void MainWindow::on_actionSave_triggered()
{
    std::string time_ff = getTime(false);
    QString filename = QString::fromStdString(time_ff + ".bmp");
    plot->getBody()->saveBmp(filename,1000,1000,2,99);
}


void MainWindow::on_action_assis_triggered(bool checked)
{
    plot->showTracer(checked);  // 显示辅助跟踪线
}

void MainWindow::on_action_import_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,
          tr("Open Project"), "", tr(u8"csv 格式 (*.*)"));

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("Error"),
                                   tr(u8"导入文件失败:\n%1").arg(fileName));
        return;
    }

    // ui->tableWidget->setRowCount()
    ui->tableWidget->clearContents();
    ui->tableWidget->setCurrentCell(0,0);

    QString files;
    while (!file.atEnd()) {
      QByteArray line = file.readLine();
      files+=line;
    }
    Clip2Table(files);
}

void MainWindow::on_action_save_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this,
          tr("Save Project"), "data/", tr("zxf Project (*.zxf)"));

    QFile file(fileName+".zxf");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("Write File"),
                                   tr("Cannot open file:\n%1").arg(fileName));
        return;
    }
    auto f = Table2Str();
    QTextStream out(&file);
    out << f;
    file.close();
}


QString MainWindow::Table2Str()
{
    QString clipText;
    int rows = ui->tableWidget->columnCount();
    int cols = ui->tableWidget->rowCount();
    for (int i=0;i<=cols;i++) {
        for (int j=0;j<=rows;j++) {
            QString text;
            if( ui->tableWidget->item(i,j)!=nullptr )//这个很重要
                text = ui->tableWidget->item(i,j)->text();
            clipText.append(text);
            clipText.append("\t");
        }
        clipText.chop(1);//删除末尾一个字符
        clipText.append("\n");
    }
    return  clipText;
}

// 清空表格显示和旧的数据
void MainWindow::clearCharts()
{
    plot->curData[0].clear();
    plot->curData[1].clear();
    plot->curData[2].clear();
    plot->curData[3].clear();
    plot->getBody()->clearGraphs();
    plot->getBody()->addGraph();
    plot->getBody()->replot();
}

void MainWindow::on_actionClear_triggered()
{
    clearCharts();
}

void MainWindow::on_actionLine_triggered()
{
    plot->SetStyle(S_LINE);
}

void MainWindow::on_actionNone_triggered()
{
    plot->SetStyle(S_NONE);
}

void MainWindow::on_actionVersion_triggered()
{
     QMessageBox::about(this,u8"关于",u8"张xx Creat By 424358225@qq.com");
}


void MainWindow::on_action_hide_triggered(bool checked)
{
    // checked ? ui->action_hide->setText("隐藏"):ui->action_hide->setText("显示");
    plot->installEvent(checked);
}

void MainWindow::on_actionGridVisible_toggled(bool arg1)
{
    plot->SetGridVisible(arg1);
}
